//
//  LLEmoticon.swift
//  表情键盘
//
//  Created by Bingo on 15/11/5.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit

class LLEmoticonPackage: NSObject {
    
    private static let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
    
    var id:String?
 
//    var removeEmotion:Bool = false
    
    var group_name_cn:String?
    
    
    var emoticons: [LLEmoticon]?
    
    init(id:String){
        self.id = id
        super.init()
    
    }
    
//    init(removeEmoticon:Bool) {
//        self.removeEmotion = removeEmoticon
//        
//        super.init()
//    }
    
    override var description:String{
    
        return "\n\t表情包模型：id:\(id),group_name_cn\(group_name_cn),emoticons\(emoticons)"
    }
    
    static let packages: [LLEmoticonPackage] = LLEmoticonPackage.Loadpackages()
    
      private class func Loadpackages() -> [LLEmoticonPackage] {
        
        let plistPath = bundlePath + "/emoticons.plist"
        
        let plistDict = NSDictionary(contentsOfFile: plistPath)!
        
        var packages = [LLEmoticonPackage]()
        
        let recent = LLEmoticonPackage(id: "")
        
        recent.group_name_cn = "最近"
        
        packages.append(recent)
        
        recent.emoticons = [LLEmoticon]()
        
        recent.appendEmptyEmotion()
        
        if let packagesArray = plistDict["packages"] as? [[String: AnyObject]]{
        
            for dict in packagesArray{
            
                let id = dict["id"] as!String
                
                let package = LLEmoticonPackage(id: id)
                
                
                package.loadEmoticon()
                
                packages.append(package)
                
            }
        
        }
        return packages
    }
    
    func loadEmoticon(){
        
        let infoPath = LLEmoticonPackage.bundlePath + "/" + id! + "/info.plist"
        
        let infoDict = NSDictionary(contentsOfFile: infoPath)!
        
        group_name_cn = infoDict["group_name_cn"] as? String
        
//        let emoticonsArr = infoDict["emoticons"] as! [[String:String]]
        
        emoticons = [LLEmoticon]()
        
        var index = 0
        
        if let array = infoDict["emoticons"]as?[[String:String]]{
            for dict in array{
                emoticons?.append(LLEmoticon(id: id!, dict: dict))
                
                index++
                
                    if index == 20{
                    
                        emoticons?.append(LLEmoticon(removeEmoticon: true))
                        
                        index = 0
                }
            }
        }
        appendEmptyEmotion()
    }
    
    private func appendEmptyEmotion(){
        
        let count = emoticons!.count % 21
        
        if count > 0 || emoticons!.count == 0{
        
            for _ in count..<20{
                emoticons?.append(LLEmoticon(removeEmoticon: false))
            
            }
            
            emoticons?.append(LLEmoticon(removeEmoticon: true))
        }
        
    }

    class func addFavorate (emoticon:LLEmoticon) {
        
        if emoticon.removeEmoticon{
            return
        }
        
        emoticon.times++
        
        var recentEmoticons = packages[0].emoticons
        
        let removerEmoticon = recentEmoticons!.removeLast()
        
        let contains = recentEmoticons!.contains(emoticon)
        
        if !contains{
        
            recentEmoticons?.append(emoticon)
        }
        
        recentEmoticons = recentEmoticons?.sort({ (e1, e2) -> Bool in
            return e1.times > e2.times
        })
        
        if !contains{
            recentEmoticons?.removeLast()
        }
        
        
        recentEmoticons?.append(removerEmoticon)
        
        packages[0].emoticons = recentEmoticons
        
        print("packages[0].emoticons:\(packages[0].emoticons)")
        print("packages[0].emoticons count: \(packages[0].emoticons?.count)")
    }
}


class LLEmoticon: NSObject {
    
    var id:String?
    
    var chs:String?
    
    var png:String?{
    
        didSet{
            
            pngPath = LLEmoticonPackage.bundlePath + "/" + id! + "/" + png!
//            print("pngPath\(pngPath)")
        
        }
    }
    
    var pngPath:String?
    
    
    var code:String?{
        didSet{
            guard let co = code else{
            
                return
            }
            
            let scanner = NSScanner(string: co)
            
            var value:UInt32 = 0
            
            scanner.scanHexInt(&value)
            
            let c = Character(UnicodeScalar(value))
            
            emoji = String(c)
        
        }
    
    }
    
    var emoji:String?
    
    var removeEmoticon:Bool = false
    
    var times = 0
    
    init(removeEmoticon:Bool){
        self.removeEmoticon = removeEmoticon
        
        super.init()
    
    }

    init(id:String,dict:[String:String]){
        self.id = id
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description:String{
    
        return "\n\t\t表情模型：chs: \(chs), png: \(png), code: \(code)),removeEmoticon: \(removeEmoticon), times:\(times)"
    
    }
    
    func emoticonToAttrString(font:UIFont) -> NSAttributedString{
        
        guard let pngP = pngPath else{
        
            return NSAttributedString(string: "")
        }
    
            
            let attachment = LLTextAttachment()
            
            let image = UIImage(contentsOfFile: pngP)
            
            attachment.image = image
            
            attachment.name = chs
            
            let height = font.lineHeight ?? 10
            
            attachment.bounds = CGRect(x: 0, y: -(height * 0.25), width: height, height: height)
            
            let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            
            attrString.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: 1))
    
        return attrString
    }
    
    class func emotionStringToEmotion(emotionString:String) ->LLEmoticon? {
        
        var emoticon:LLEmoticon?
        
        for package in LLEmoticonPackage.packages{
        
            let result = package.emoticons?.filter({ (e1) -> Bool in
                return e1.chs == emotionString
            })
            
            emoticon = result?.first
            
            if emoticon != nil{
                
                break
            }
        
        }
        
        return emoticon
    }
    
    
    class func emticonStringToEmotionAttrString(string:String,font:UIFont) -> NSAttributedString {
        
        let pattern = "\\[.*?\\]"
        
        let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        
        let results = regular.matchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: string.characters.count))
        
        var attrText = NSMutableAttributedString(string: string)
        
        var count = results.count
        while count > 0{
        
            let result = results[--count]
             
            let range = result.rangeAtIndex(0)
            
            let emoticonString = (string as NSString).substringWithRange(range)
            
            
            if let emoticon = LLEmoticon.emotionStringToEmotion(emoticonString)
            {
                let attrString = emoticon.emoticonToAttrString(font)
                
                attrText.replaceCharactersInRange(range, withAttributedString: attrString)
                
            }
        }
        return attrText
    }

}